<template>
	<div class="page">
		<div class="page-header">
			<h1 class="page-title">教材/专著管理</h1>
			<p class="page-subtitle">审核教职工提交的教材/专著信息，按条件筛选</p>
		</div>

		<el-card class="mb16">
			<el-form :inline="true" :model="query" label-width="80px">
				<el-form-item label="类型"><el-input v-model="query.textbookType" placeholder="如 规划教材" style="width: 160px" /></el-form-item>
				<el-form-item label="级别">
					<el-select v-model="query.level" clearable placeholder="全部" style="width: 140px">
						<el-option label="校级" value="校级" />
						<el-option label="省部级" value="省部级" />
						<el-option label="国家级" value="国家级" />
					</el-select>
				</el-form-item>
				<el-form-item label="状态">
					<el-select v-model="query.status" clearable placeholder="全部" style="width: 140px">
						<el-option label="待审核" value="PENDING" />
						<el-option label="已通过" value="APPROVED" />
						<el-option label="已驳回" value="REJECTED" />
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleSearch">查询</el-button>
					<el-button @click="resetQuery">重置</el-button>
				</el-form-item>
			</el-form>
		</el-card>

		<el-card>
			<el-table :data="tableData" style="width: 100%">
				<el-table-column prop="userName" label="教师" width="120" />
				<el-table-column prop="title" label="书名" min-width="220" show-overflow-tooltip />
				<el-table-column prop="isbn" label="ISBN" min-width="160" show-overflow-tooltip />
				<el-table-column prop="publisher" label="出版社" min-width="160" show-overflow-tooltip />
				<el-table-column prop="publishDate" label="出版日期" width="120" />
				<el-table-column prop="textbookType" label="类型" width="120" />
				<el-table-column prop="level" label="级别" width="100" />
				<el-table-column prop="status" label="状态" width="110">
					<template #default="{ row }">
						<el-tag :type="statusTag(row.status)">{{ statusText(row.status) }}</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="280">
					<template #default="{ row }">
						<el-button size="small" @click="openAuthors(row)">作者</el-button>
						<el-button size="small" type="primary" @click="openAttachments(row)">附件</el-button>
						<el-button size="small" type="warning" :disabled="row.status!=='PENDING'" @click="openReview(row)">审核</el-button>
						<el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>

			<div style="margin-top: 16px; display: flex; justify-content: flex-end;">
				<el-pagination background layout="prev, pager, next, jumper, ->, total" :total="total" :page-size="size" :current-page="page" @current-change="handlePageChange" />
			</div>
		</el-card>

		<el-dialog v-model="showAttach" title="附件管理" width="680px">
			<el-table :data="attachList" size="small">
				<el-table-column prop="fileName" label="文件名" min-width="280" show-overflow-tooltip />
				<el-table-column label="操作" width="200">
					<template #default="{ row }">
						<el-button size="small" @click="downloadAttachment(row)">下载</el-button>
						<el-button size="small" type="danger" @click="deleteAttachment(row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<template #footer><el-button @click="showAttach=false">关闭</el-button></template>
		</el-dialog>

		<el-dialog v-model="authorsDialogVisible" title="作者/编者" width="640px">
			<el-table :data="authors" size="small" style="width:100%">
				<el-table-column prop="author_name" label="姓名" width="180" />
				<el-table-column prop="role" label="角色" width="150" />
				<el-table-column prop="in_campus_rank" label="校内排名" width="120" />
				<el-table-column prop="word_count" label="字数(千字)" width="120" />
			</el-table>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="authorsDialogVisible = false">关 闭</el-button>
					<el-button type="primary" @click="exportAuthorsCsv">导出CSV</el-button>
				</span>
			</template>
		</el-dialog>

		<el-dialog v-model="reviewDialogVisible" title="审核" width="480px">
			<el-form label-width="80px">
				<el-form-item label="结果">
					<el-radio-group v-model="reviewAction">
						<el-radio label="APPROVED">通过</el-radio>
						<el-radio label="REJECTED">驳回</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="意见">
					<el-input v-model="reviewOpinion" type="textarea" rows="3" placeholder="可选" />
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="reviewDialogVisible=false">取 消</el-button>
				<el-button type="primary" @click="submitReview">确 定</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { textbookApi } from '@/api/textbook'

const query = reactive({ textbookType: '', level: '', status: '' })
const page = ref(1)
const size = ref(10)
const total = ref(0)
const tableData = ref([])

const showAttach = ref(false)
const attachList = ref([])
const currentRow = ref(null)

const authorsDialogVisible = ref(false)
const authors = ref([])
const authorsBelongTitle = ref('')
const reviewDialogVisible = ref(false)
const reviewAction = ref('APPROVED')
const reviewOpinion = ref('')

const statusTag = (s) => ({ 'PENDING': 'warning', 'APPROVED': 'success', 'REJECTED': 'danger' }[s] || 'info')
const statusText = (s) => ({ 'PENDING': '待审核', 'APPROVED': '已通过', 'REJECTED': '已驳回' }[s] || s)

const parsePageResult = (res) => {
	const list = Array.isArray(res?.data) ? res.data : (Array.isArray(res) ? res : (Array.isArray(res?.list) ? res.list : []))
	tableData.value = list
	total.value = (typeof res?.total === 'number') ? res.total : (typeof res?.data?.total === 'number' ? res.data.total : list.length)
}

const loadTable = async () => {
	const res = await textbookApi.listAll({ ...query, page: page.value, size: size.value })
	parsePageResult(res)
}

const handleSearch = () => { page.value = 1; loadTable() }
const resetQuery = () => { Object.assign(query, { textbookType: '', level: '', status: '' }); page.value = 1; loadTable() }
const handlePageChange = (p) => { page.value = p; loadTable() }

const handleReview = async (row, action) => {
	try {
		await ElMessageBox.confirm(`确认${action==='APPROVED'?'通过':'驳回'}该记录吗？`, '审核确认', { type: 'warning' })
		await textbookApi.review(row.id, { action })
		ElMessage.success('操作成功')
		await loadTable()
	} catch (e) { if (e !== 'cancel') ElMessage.error(e?.response?.data || e?.message || '操作失败') }
}

const openAttachments = async (row) => {
	currentRow.value = row
	const res = await textbookApi.listAttachments(row.id)
	attachList.value = Array.isArray(res?.data) ? res.data : (Array.isArray(res) ? res : [])
	showAttach.value = true
}

const downloadAttachment = async (row) => {
	const resp = await textbookApi.downloadAttachment(currentRow.value.id, row.id)
	const blob = resp?.data || resp
	const url = window.URL.createObjectURL(blob)
	const a = document.createElement('a')
	a.href = url
	a.download = row.fileName || 'download'
	document.body.appendChild(a)
	a.click()
	window.URL.revokeObjectURL(url)
	document.body.removeChild(a)
}

const deleteAttachment = async (row) => {
	await ElMessageBox.confirm('确定删除该附件吗？', '删除确认', { type: 'warning' })
	await textbookApi.deleteAttachment(currentRow.value.id, row.id)
	ElMessage.success('已删除')
	await openAttachments(currentRow.value)
}

const openAuthors = async (row) => {
	authorsDialogVisible.value = true
	authorsBelongTitle.value = row.title
	try {
		const res = await textbookApi.listAuthors(row.id)
		const list = Array.isArray(res?.data) ? res.data : (Array.isArray(res) ? res : [])
		authors.value = list.map(a => ({
			author_name: a.author_name ?? a.authorName,
			in_campus_rank: a.in_campus_rank ?? a.inCampusRank,
			role: a.role,
			word_count: a.word_count ?? a.wordCount
		}))
	} catch (e) {
		ElMessage.error('获取作者失败')
	}
}

const exportAuthorsCsv = () => {
	const header = ['书名','姓名','角色','校内排名','字数(千字)']
	const rows = authors.value.map(a => [authorsBelongTitle.value, a.author_name || '', a.role || '', a.in_campus_rank ?? '', a.word_count ?? ''])
	const csv = [header, ...rows].map(r => r.map(x => {
		const s = String(x ?? '')
		return /[",\n]/.test(s) ? '"' + s.replaceAll('"','""') + '"' : s
	}).join(',')).join('\n')
	const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
	const url = URL.createObjectURL(blob)
	const a = document.createElement('a')
	a.href = url
	a.download = `${authorsBelongTitle.value}-作者列表.csv`
	document.body.appendChild(a)
	a.click()
	document.body.removeChild(a)
	URL.revokeObjectURL(url)
}

const openReview = (row) => {
	currentRow.value = row
	reviewAction.value = 'APPROVED'
	reviewOpinion.value = ''
	reviewDialogVisible.value = true
}

const submitReview = async () => {
	try {
		await textbookApi.review(currentRow.value.id, { action: reviewAction.value, opinion: reviewOpinion.value || null })
		ElMessage.success('审核完成')
		reviewDialogVisible.value = false
		await loadTable()
	} catch (e) {
		ElMessage.error(e?.response?.data || e?.message || '审核失败')
	}
}

const handleDelete = async (row) => {
	try {
		await ElMessageBox.confirm('确定删除该记录吗？', '删除确认', { type: 'warning' })
		await textbookApi.remove(row.id)
		ElMessage.success('已删除')
		await loadTable()
	} catch (e) {
		if (e !== 'cancel') ElMessage.error(e?.response?.data || e?.message || '删除失败')
	}
}

loadTable()
</script>

<style scoped>
.mb16 { margin-bottom: 16px; }
.page-header { margin-bottom: 16px; }
.page-title { margin: 0; font-size: 20px; }
.page-subtitle { margin: 4px 0 0 0; color: #666; }
</style> 